const { User } = require("../database/sequlize");
const bcrypt = require("bcrypt");
const defaultConfig = require("../config/defaultConfig");
const jwt = require("jsonwebtoken");

// 校验用户账号密码是否正确
exports.authenticateUser = async (params) => {
  const { username, password } = params;
  const user = await User.findOne({ where: { username: username } });
  if (!user) {
    throw new Error("No user found with that username");
  }
  const isValid = await bcrypt.compare(password, user.password);

  if (!isValid) {
    throw new Error("Invalid password");
  }

  return user;
};

// 注册用户
exports.createUser = async (params) => {
  const { username, password } = params;

  // 最少 6 位 至少包含一个大写 一个小写 一个数字 一个特殊字符
  const reg =
    /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/;

  if (!reg.test(password)) {
    throw new Error("Password format error");
  }

  const hashedPassword = await bcrypt.hash(password, defaultConfig.saltRounds);
  return User.create({
    username,
    password: hashedPassword,
  });
};

// 设置 token
exports.generateToken = (user) =>
  jwt.sign({ id: user.id, username: user.username }, defaultConfig.secret, {
    expiresIn: "12h", // 设置令牌的过期时间
  });
